package com.sgj.controller;

import com.sgj.pojo.Type;
import com.sgj.service.BlogService;
import com.sgj.service.TypeService;
import com.sgj.vo.BlogRes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.List;

/**
 * @author 沈国纪
 * @date 2021/4/4 22:14
 */
@Controller
public class TypeShowController {

	private static final String TYPE = "types";

	@Autowired
	private TypeService typeService;

	@Autowired
	private BlogService blogService;

	/**
	 * 根据分类查询博客
	 * @param pageable
	 * @param id
	 * @param model
	 * @return
	 */
	@GetMapping("/types/{id}")
	public String types(@PageableDefault(size = 6, sort = {"updateTime"}, direction = Sort.Direction.DESC) Pageable pageable,
	                    @PathVariable Long id, Model model) {
		// 指定足够大的分类数量
		List<Type> types = typeService.listTypeTop(30000);
		if (id == -1) {
			id = types.get(0).getId();
		}
		BlogRes blogRes = new BlogRes();
		blogRes.setTypeId(id);
		model.addAttribute("types", types);
		model.addAttribute("page", blogService.listBlog(pageable, blogRes));
		model.addAttribute("activeTypeId", id);
		return TYPE;
	}
}
